const http = {
  get: async (url, options) => {
    const asyncFetch = fetch(url, {
      ...options,
      credentials: 'include',
    });

    asyncFetch.catch(ex => 'get');

    return asyncFetch;
  },
  postForm: async (url, data, options, timeout) => {
    const formData = Object.entries(data || {});
    const params = new URLSearchParams();
    formData.forEach(
      ([key, value]) =>
        typeof value === 'object'
          ? params.append(key, JSON.stringify(value))
          : params.append(key, value)
    );

    const asyncFetch = fetch(url, {
      credentials: 'include',
      ...options,
      method: 'post',
      body: params,
    });

    asyncFetch.catch(ex => 'postForm');
    return asyncFetch;
  },

  postJson: async (url, data, options) => {
    let { headers } = options || {};
    headers = headers || {};
    const asyncFetch = fetch(url, {
      ...options,
      credentials: 'include',
      method: 'post',
      headers: {
        ...headers,
        'Content-Type': 'application/json; charset=utf-8',
      },
      body: JSON.stringify(data),
    });

    asyncFetch.catch(ex => 'postJson');
    return asyncFetch;
  },

  /**
   * 针对卡管系统处理
   * @param url
   * @param data
   * @param options
   * @returns {Promise<Object>}
   */
  postCardFormData: async (url, data, options) => {
    let body = data;
    if (typeof data === 'object') {
      body = JSON.stringify(data);
    }

    let response = null;

    const asyncHttp = fetch(url, {
      ...options,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      credentials: 'include',
      body,
    });

    asyncHttp.catch(ex => console.log(ex));

    response = await asyncHttp;

    return response;
  },
};

export default http;
